from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated
from utils.viewset import CustomModelViewSet
from system.home.models import Notice
from system.home.serializers import NoticeSerializer, NoticeUpdateSerializer
from utils.json_response import SuccessResponse, ErrorResponse
import json


class NoticeViewSet(CustomModelViewSet):
    queryset = Notice.objects.all()
    serializer_class = NoticeSerializer
    update_serializer_class = NoticeUpdateSerializer
    permission_classes = [IsAuthenticated]

    def partial_update(self, request, *args, **kwargs):
        notice = Notice.objects.filter(id=kwargs.get('pk')).first()
        read = request.data.get('read')
        sort = request.data.get('sort')
        if not notice:
            return ErrorResponse(message='未找到指定记录')
        if sort:
            if sort == 'up':
                tmp = Notice.objects.filter(sort_id__gt=notice.sort_id).last()
            else:
                tmp = Notice.objects.filter(sort_id__lt=notice.sort_id).first()
            if tmp:
                print(tmp.id)
                tmp.sort_id, notice.sort_id = notice.sort_id, tmp.sort_id
                tmp.save()
        if read:
            read_ids = json.loads(notice.read_ids)
            read_ids.append(str(request.user.id))
            notice.read_ids = json.dumps(read_ids)
        notice.save()
        return SuccessResponse(data='', message="更新成功")
